<template>
    <view class="cart">
		<!-- 没有商品时 -->
		<empty v-show="!isempty">

		</empty>
		
        <view class="content" v-show="isempty">
            <view class="list" v-for="item in list" :key='item.cartId' >
                <view class="left">
                    <checkbox-group @change="checkboxChange($event,item.cartId)">
                        <checkbox :value="item.cartId" :checked="item.isChecked" />
                    </checkbox-group>
                    <image :src="item.cartImgUrl" class="img"></image>
                </view>
                <view class="center" @tap="gotoPro(item.cartProductByStore,item.cartProductId)">
                    <view class="name">
                        {{item.cartProductName}}
                    </view>
                    <view class="size">
        规格：颜色: {{item.cartProductColor}},年龄: {{item.cartProductAge}},性别: {{item.cartProductGender}}
                    </view>
                    <view class="count">
                        数量：x{{item.cartProductNum}}
                    </view>
                </view>
                <view class="right">
					<!-- <span style="font-size: 18rpx;">{{ item.cartCreateTime }}</span> -->
                    <view class="price" style="color: red">
                        单价￥{{item.cartCurrentPrice}}元
                    </view>
                    <view class="update-count">
                        <view class="reduce" @tap="editNum(item.cartId,-1)">
                            -
                        </view>
                        <view class="cart-count">
                            {{item.cartProductNum}}
                        </view>
                        <view class="add" @tap="editNum(item.cartId,1)">
                            +
                        </view>
                    </view>
                </view>
            </view>
        </view>
          <displayList>
			  <view slot="listName">猜你喜欢</view>
		  </displayList>
        <!-- 底部导航栏 -->
        <view class="tabbar" v-show="isempty">
            <view class="all">
                <checkbox-group @change="checkboxChangeAll">
                    <checkbox :checked="isAllChecked" />全选
                </checkbox-group>
            </view>
            <view class="totalPrice">
                总价:￥{{totalPrice}}元
            </view>
            <view class="submitOrder" @tap="submitOrder" v-show="isShow">
                去结算
            </view>
			<view class="deleteOrder" @tap="deleteOrder" v-show="!isShow">
			    删除
			</view>
        </view>
    </view>
</template>

<script>
	import displayList from '../../components/displayList.vue';
	import {
		store
	} from '@/uni_modules/uni-id-pages/common/store.js';
	import {
		get,
		post,
		setToken
	} from '@/utils/api.js';
	import empty from '../../components/empty.vue'
    export default {
		components:{
			empty,
			displayList
		},
		computed: {
		  formattedDates() {
		    // 创建一个空对象来保存格式化后的日期
		    const formattedDates = {};
		
		    // 遍历你的列表
		    this.list.forEach((item) => {
		      // 使用 moment.js 或者 Date 对象来格式化日期
		      // 这里我们使用原生 JavaScript 的 Date 对象
		      const date = new Date(item.cartCreatetime);
		      const year = date.getFullYear();
		      const month = ('0' + (date.getMonth() + 1)).slice(-2); // 加1是因为月份是从0开始的
		      const day = ('0' + date.getDate()).slice(-2);
		      const hours = ('0' + date.getHours()).slice(-2);
		      const minutes = ('0' + date.getMinutes()).slice(-2);
		      const seconds = ('0' + date.getSeconds()).slice(-2);
		
		      // 格式化日期
		      const formattedDate = `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`;
		
		      // 将格式化后的日期保存在对象中，键是 item 的 id
		      formattedDates[item.id] = formattedDate;
		    });
		
		    // 返回格式化后的日期对象
		    return formattedDates;
		  }
		},
		onShow() {
			this.getMyShopCart()
		},
        data() {
            return {
                list: [], //列表数据
                isAllChecked: false, //是否全选
                totalPrice: 0, //总价
				isEditStatus: true, // 当前页面状态 默认是信息显示页面
				isShow:true,
				isempty:true ,
				address:{}
            }
        },
			// 按钮监听函数
			onNavigationBarButtonTap(e) {//不需要在<view>里面做任何操作，可直接引用
				let rightText = ''
				if(this.isEditStatus){//根据定义Boolean变量值，可多次切换文字
					rightText = '退出'
					this.isShow = false
				}else{
					rightText = '管理'
					this.isShow = true
				}
				this.isEditStatus = !this.isEditStatus
				const currentWebview = this.$mp.page.$getAppWebview();
				//下面的方法即可修改文字内容及颜色等,e.index就表示修改当前点击按钮样式
				currentWebview.setTitleNViewButtonStyle(e.index, { //h5端会报错
					text: rightText
				});
			},
			created() {
				this.getMyShopCart()
				// console.log(this.orderNumberCreate())
				this.getMydefultAddress()
				this.countShopNum()
			},
        methods: {
			gotoPro(cartProductByStore,cartProductId) {
				uni.setStorageSync('productId',cartProductId)
				uni.setStorageSync('productByStore',cartProductByStore)
				uni.redirectTo({
					url:'/pages/proDetail/proDetail'
				})
			},
			getMyShopCart() {
				post('/cart/getCartByUserName', 
				{
				  cartUser:store.userInfo.username	
				}
				, {
				needToken: true, 		
				 success: (res) => {
				  	if (res.statusCode === 200) {
					 this.list = res.data.data.map(item => ({
						 ...item, // 复制对象的所有属性
					 isChecked: false, // 添加 isChecked 属性并设为 false
				 }));
				}
				if(!this.List)
				this.isempty = !this.isempty
				}
				});  
			},
			countShopNum()
			{
				post('/cart/getCartCountByUserName',
				 {
					 cartUser:store.userInfo.username
				 }
				 , {
				  needToken: true, 	
					success: (res) => {
					if (res.statusCode === 200) {
						if(res.data.data === '购物车为空') {
						uni.setStorageSync('shopNum',0)	
						}
						else{
						uni.setStorageSync('shopNum',res.data.data)		
						}
						console.log(res.data.data)
						}
					}
				}); 
			},
			gotoClose() {
				// 检查是否有商品被选中
					const hasSelectedItems = this.list.some(el => el.isChecked);
				    
					if (!hasSelectedItems) {
						// 如果没有任何商品被选中，提示用户
						uni.showToast({
							title: "请至少选择一件商品",
							icon: "none",
							duration: 2000
						});
					} else {
				// 收集所有被选中的商品的 cartId
				const selectedCartIds = this.list
				    .filter(item => item.isChecked)
				    .map(item => item.cartId);
                 post('/order/addOrder',
                 {
                   cartList:selectedCartIds
                 }
                 , {
                 needToken: true, 		
                  success: (res) => {
                   	if (res.statusCode === 200) {
                 }
                 }
                 });  
			  	}
				},
            setCart() { //计算总价
                let totalPrice = 0
                this.list.forEach(v => {
                    if (v.isChecked) {
                        totalPrice += v.cartProductNum * v.cartCurrentPrice
                    }
                })
                this.totalPrice = totalPrice
            },

            editNum(id, type) { //编辑数量
                const index = this.list.findIndex(v => v.cartId == id)
                if (this.list[index].cartProductNum == 1 && type == -1) {
                    uni.showToast({
                        title: '至少购买一件商品',
                        icon: 'none'
                    })
                } else {
                    this.list[index].cartProductNum += parseInt(type)
					this.updateShopCart(id,this.list[index].cartProductNum)
                }
                this.setCart()
            },
            //订单编号生成 当前时间精确到秒+当前时间戳
			 orderNumberCreate() {
				    const now = new Date();
				    const dateTimeStr = `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}${now.getSeconds().toString().padStart(2, '0')}`;
				    const milliseconds = now.getMilliseconds().toString().padStart(3, '0');
				    return `${dateTimeStr}${milliseconds}`; 
			 },
            // 全选
            checkboxChangeAll(e) {
                this.isAllChecked = !this.isAllChecked
                this.list.forEach(v => v.isChecked = this.isAllChecked)
				        // 收集所有商品的 cartId
				        const selectedCartIds = this.list
				            .filter(item => item.isChecked)
				            .map(item => item.cartId);
				        
				        // console.log('Selected cartIds:', selectedCartIds);
                this.setCart()
            },
            //商品数量更新
			updateShopCart(cartId,cartProductNum) {
				post('/cart/updateCart', 
				{
				  cartId:cartId,
				  cartProductNum:cartProductNum
				}, {
				  needToken: true, 
					success: (res) => {
					if (res.statusCode === 200) {
					  console.log('数量更新成功');
					}
				  }
				});  
			},
            // 选择每一项
            checkboxChange: function(e, id) {
                var temp = []
                // 找到被修改的商品对象
                let index = this.list.findIndex(v => v.cartId === id)
                // 选中状态取反
                this.list[index].isChecked = !this.list[index].isChecked

                temp = this.list.every(v => v.isChecked)
                if (temp) {
                    this.isAllChecked = true
                } else {
                    this.isAllChecked = false
                }
                this.setCart()
            },
            getMydefultAddress() {
            post('/address/default',
            {
             username:store.userInfo.username
            }, {
              needToken: true, 
            	success: (res) => {
            	if (res.statusCode === 200) {
            		this.address = res.data 
            	}
              }
            }); 	
            },
			// countShopNum()
			// {
			// 	post('/cart/getCartCountByUserName',
			// 	 {
			// 		 cartUser:store.userInfo.username
			// 	 }
			// 	 , {
			// 	  needToken: true, 	
			// 		success: (res) => {
			// 		if (res.statusCode === 200) {
			// 			uni.setStorageSync('shopNum',res.data.data)		
			// 			}
			// 		}
			// 	}); 
			// },
            submitOrder() { // 提交购物车订单
                // 判断是否选择购物车商品
                var bol = this.list.every(el => el.isChecked == false)
                if (bol) {
                    uni.showToast({
                        title: "这些你都不喜欢吗,你倒是选一个啊商品啊",
                        icon: "none",
                        duration: 2000
                    })
                } else {
				// 检查是否有商品被选中
				const hasSelectedItems = this.list.some(el => el.isChecked);

				if (!hasSelectedItems) {
					// 如果没有任何商品被选中，提示用户
					uni.showToast({
						title: "请至少添加一件商品",
						icon: "none",
						duration: 2000
					});
				} else {
					// 收集所有被选中的商品的完整信息，添加新属性，并删除 isChecked 属性
					let tempOrder = this.orderNumberCreate()
					uni.setStorageSync('uid',tempOrder)
					const selectedItems = this.list
						.filter(item => item.isChecked)
						.map(item => {
							let newItem = {...item, oid: tempOrder,addressId: this.address.addressId,ordersStatus:'待支付'};
							delete newItem.isChecked; // 删除 isChecked 属性
							delete newItem.cartProductByStore; 
							delete newItem.cartCreatetime;
							return newItem;
						}); 
						const newKeys = {
						    cartId: 'cartId',
						    cartProductId: 'ordersProductId',
						    cartProductName: 'ordersProductName',
						    cartProductColor: 'ordersProductColor',
						    cartProductAge: 'ordersProductAge',
						    cartProductGender: 'ordersProductGender',
						    cartProductNum: 'ordersProdNumber',
						    cartUser: 'ordersUser',
						    cartCurrentPrice: 'ordersCurrentPrice',
						    oid: 'oid'
						};
						let updatedSelectedItems = selectedItems.map(item => {
						    let newItem = {};
						    for (let oldKey in item) {
						        if (item.hasOwnProperty(oldKey) && oldKey !== 'cartId') { // 排除cartId
						            let newKey = newKeys[oldKey] || oldKey;
						            newItem[newKey] = item[oldKey];
						       }
						    }
						    return newItem;
						});
						console.log(updatedSelectedItems)
						post('/order/addOrder', updatedSelectedItems, {
						  needToken: true, 
							success: (res) => {
						if (res.statusCode === 200) {
							 console.log('订单生成成功');
							}
						}
						}); 
						// 收集所有被选中的商品的 cartId
						const selectedCartIds = this.list
						    .filter(item => item.isChecked)
						    .map(item => item.cartId);
							//转为多个对象含有cardId属性
							const transformedCartIds = selectedCartIds.map(id => ({ cartId: id }))
						
						 this.deleteShopCart(transformedCartIds)
						uni.navigateTo({
							url:'/pages/editOrder/editOrder'
						})
				}
            }
			},
			     deleteShopCart(selectedCartIds) {
				post('/cart/deleteCartList', selectedCartIds, {
				  needToken: true, 
							  success: (res) => {
								if (res.statusCode === 200) {
								  console.log('删除成功');
								}
							  }
				});  
				uni.setStorageSync("shopNum",uni.getStorageSync("shopNum") - selectedCartIds.length)
				console.log(uni.getStorageSync("shopNum"))
			},
			deleteOrder() {
				// 检查是否有商品被选中
				const hasSelectedItems = this.list.some(el => el.isChecked);
                
				if (!hasSelectedItems) {
					// 如果没有任何商品被选中，提示用户
					uni.showToast({
						title: "请至少选择一件商品进行删除",
						icon: "none",
						duration: 2000
					});
				} else {
            // 收集所有被选中的商品的 cartId
            const selectedCartIds = this.list
                .filter(item => item.isChecked)
                .map(item => item.cartId);
				//转为多个对象含有cardId属性
				const transformedCartIds = selectedCartIds.map(id => ({ cartId: id }))

             this.deleteShopCart(transformedCartIds)
            // 删除所有选中的商品
            this.list = this.list.filter(el => !el.isChecked);
            // 提示删除成功
            uni.showToast({
                title: "已成功删除商品",
                icon: "success",
                duration: 2000
            });
				}

			}
			},
    }
</script>
<style lang="scss" scoped>
    page {
        background: #f1e8e7;
    }
    .content {
        width: 670rpx;
        margin: 0 auto 180rpx;
    }

    // 居中显示
    @mixin textCenter {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .list {
        width: 672rpx;
        height: 208rpx;
        background: #f9f9f9;
        box-shadow: 0 8rpx 16rpx 0 rgba(83, 66, 49, 0.08);
        border-radius: 24rpx;
        margin-top: 32rpx;
        display: flex;
        justify-content: space-around;
        align-items: center;

        .left {
            display: flex;

            .img {
                width: 136rpx;
                height: 136rpx;
                margin-left: 10rpx;
                border-radius: 8%;
            }
			
        }

        .center {
            width: 170rpx;

            .name {
                font-size: 26rpx;
                color: #3E3E3E;
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
            }

            .size,
            .count {
                font-size: 22rpx;
                color: #8D8D8D;
            }
        }

        .right {
            .price {
                margin-top: 40rpx;
                font-size: 26rpx;
                margin-left: 40rpx;
            }

            // 加减数量
            .update-count {
                margin-top: 40rpx;
                display: flex;

                .reduce,
                .add {
                    width: 40rpx;
                    height: 40rpx;
                    background: #F1ECE7;
                    border-radius: 21.6rpx;
                    color: #979797;
                    @include textCenter;
                    font-size: 50rpx;
                }

                .cart-count {
                    width: 72rpx;
                    height: 40rpx;
                    line-height: 40rpx;
                    background: #F1ECE7;
                    border-radius: 21.6rpx;
                    margin-left: 18rpx;
                    margin-right: 18rpx;
                    text-align: center;
                }
            }
        }
    }

    // 底部导航
    .tabbar {
        width: 100%;
        height: 176rpx;
        background-color: #f3f3f3;
        position: fixed;
        bottom: 0rpx;
        display: flex;
        align-items: center;
        justify-content: space-around;
        border-radius: 8% 8%;

        .all {
            font-size: 32rpx;
            color: #3E3E3E;
            letter-spacing: 2.29rpx;
            display: flex;
        }

        .totalPrice {
            font-size: 32rpx;
            color: #3E3E3E;
            letter-spacing: 2.29rpx;
            color: red;
        }

        .submitOrder {
            width: 208rpx;
            height: 80rpx;
            background: #ff5500;
            border-radius: 14rpx;
            border-radius: 14rpx;
            font-size: 36rpx;
            color: #FFFFFF;
            letter-spacing: 2.57rpx;
            display: flex;
            align-items: center;
            justify-content: center;
        }
		.deleteOrder {
			width: 208rpx;
			height: 80rpx;
			background: #ff0000;
			border-radius: 14rpx;
			border-radius: 14rpx;
			font-size: 36rpx;
			color: #FFFFFF;
			letter-spacing: 2.57rpx;
			display: flex;
			align-items: center;
			justify-content: center;	
		}
    }
</style>